﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using WWF.Contracts;
using WWF.Data;

namespace WWF.Activities
{

    public sealed class SaveApplication : CodeActivity<ApplicationResponse>
    {
        public InArgument<ApplicationRequest> AppRequest { get; set; }

        // If your activity returns a value, derive from CodeActivity<TResult>
        // and return the value from the Execute method.
        protected override ApplicationResponse Execute(CodeActivityContext context)
        {
            using (UniversityApplicationEntities entity = new UniversityApplicationEntities())
            {
                ApplicationRequest request = AppRequest.Get(context);

                var query = from a in entity.Applications
                            where a.ApplicantID == request.ApplicantID && a.IDType == request.IDType
                            select a;
                Application app = query.FirstOrDefault();
                if (app == null)
                {
                    app = entity.Applications.CreateObject();
                    app.Status = "Document Pending";
                    app.ApplicantName = request.ApplicantName;
                    app.ApplicantEmail = request.ApplicantEmail;
                    app.ApplicantID = request.ApplicantID;
                    app.IDType = request.IDType;
                    app.HighestDegree = request.HighestDegree;
                    app.Program = request.Program;
                    app.ExperienceYears = request.ExperienceYears;
                    app.MediumOfInstructionIsEnglish = request.MediumOfInstructionIsEnglish;
                    app.EngTestType = request.EngTestType;
                    app.EngTestScore = request.EngTestScore;
                    if (request.MediumOfInstructionIsEnglish)
                    {
                        app.EngTestType = null;
                        app.EngTestScore = null;
                    }

                    entity.Applications.AddObject(app);
                    entity.SaveChanges();
                    entity.Connection.Close();
                    return new ApplicationResponse()
                    {
                        ApplicationID = app.ApplicationID,
                        Status = app.Status
                    };
                }
                else
                {
                    return new ApplicationResponse()
                    {
                        Status = "Duplicated"
                    };
                }
            }
        }
    }
}
